import roleService from "@/api/services/system/roleService";
import userService, { type PageListReq } from "@/api/services/system/userService";
import UserSelector from "@/pages/components/selector/UserSelector";
import { Button, Drawer, Table } from "antd";
import { message } from "antd";
import { useEffect, useState } from "react";
import type { UserInfo } from "#/entity";

interface RoleUserProps {
	open: boolean;
	onClose: () => void;
	roleId?: string;
}

export default function RoleUser({ open, onClose, roleId }: RoleUserProps) {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		name: "",
		status: "",
		roleId: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [selectedUsers, setSelectedUsers] = useState<UserInfo[]>([]);
	const [userSelectorOpen, setUserSelectorOpen] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);

	useEffect(() => {
		if (roleId) {
			setQueryParams((prev) => ({
				...prev,
				roleId: roleId,
			}));
		}
	}, [roleId]);

	// 获取角色用户列表
	const fetchRoleUsers = async () => {
		if (!roleId) return; // 确保有 roleId 才执行

		setLoading(true);
		try {
			// 直接使用最新的 roleId 构建查询参数
			const params = {
				...queryParams,
				roleId: roleId,
			};
			const res = await userService.roleUserPageList(params);
			setSelectedUsers(res.records);
			setTotal(res.total);
		} catch (error) {
			message.error("获取用户列表失败");
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		if (open && roleId) {
			fetchRoleUsers();
		}
	}, [open, roleId, queryParams.page, queryParams.pageSize]); // 添加分页参数的依赖

	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	// 用户选择处理
	const handleUserSelect = async (users: UserInfo[]) => {
		try {
      if(roleId && users.length > 0) {
        await roleService.updateRoleUser({
          roleId: roleId,
          userIds: users.map((u) => u.id),
        });
        message.success("分配用户成功");
        setUserSelectorOpen(false);
        // 刷新已分配用户列表
        await fetchRoleUsers();
      }
		} catch (error) {
			message.error("分配用户失败");
		}
	};

  	//删除角色方法
	const handleDelete = async () => {
		try {
			setLoading(true);
			await roleService.deleteRole(selectedRowKeys);
			message.success("删除角色成功");
			setSelectedRowKeys([]); // 清空选中项
			fetchRoleUsers(); // 重新加载列表
		} catch (error) {
			message.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const userColumns = [
		{ title: "用户名", dataIndex: "name" },
		{ title: "姓名", dataIndex: "name" },
    { title: "部门", dataIndex: "orgIdName" },
		{ title: "手机号", dataIndex: "phone" }
	];

	return (
		<>
			<Drawer
				title="分配用户"
				width={720}
				open={open}
				onClose={onClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={onClose}>关闭</Button>
					</div>
				}
			>
				<div className="flex gap-2">
					<Button type="primary" onClick={() => setUserSelectorOpen(true)}>
						添加用户
					</Button>
          <Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
						删除用户
					</Button>
				</div>
        <div className="h-4" />
				<Table
					rowKey="id"
					scroll={{ x: "max-content" }}
					loading={loading}
          rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={userColumns}
					dataSource={selectedUsers}
					size="middle"
				/>
			</Drawer>

			<UserSelector
				open={userSelectorOpen}
				onCancel={() => setUserSelectorOpen(false)}
				onOk={handleUserSelect}
			/>
		</>
	);
}
